// Service Worker for offline support and caching
const CACHE_NAME = 'newtab-v1.1.0';
const STATIC_CACHE = 'static-v2';
const DYNAMIC_CACHE = 'dynamic-v2';
const IMAGE_CACHE = 'images-v1';

// 需要缓存的静态资源
const STATIC_ASSETS = [
    '/',
    '/index.html',
    '/styles.css',
    '/script.js',
    '/manifest.json'
];

// 缓存策略配置
const CACHE_STRATEGIES = {
    static: 'cache-first',
    dynamic: 'network-first',
    images: 'cache-first'
};

// 缓存时间配置（毫秒）
const CACHE_EXPIRY = {
    static: 7 * 24 * 60 * 60 * 1000, // 7天
    dynamic: 24 * 60 * 60 * 1000,    // 1天
    images: 30 * 24 * 60 * 60 * 1000  // 30天
};

// 安装事件 - 缓存静态资源
self.addEventListener('install', event => {
    if (self.location.hostname === 'localhost') {
        console.log('Service Worker 安装中...');
    }
    
    event.waitUntil(
        caches.open(STATIC_CACHE)
            .then(cache => {
                if (self.location.hostname === 'localhost') {
                    console.log('缓存静态资源');
                }
                return cache.addAll(STATIC_ASSETS);
            })
            .then(() => {
                return self.skipWaiting();
            })
            .catch(error => {
                if (self.location.hostname === 'localhost') {
                    console.error('Service Worker 安装失败:', error);
                }
            })
    );
});

// 激活事件 - 清理旧缓存
self.addEventListener('activate', event => {
    if (self.location.hostname === 'localhost') {
        console.log('Service Worker 激活中...');
    }
    
    event.waitUntil(
        caches.keys()
            .then(cacheNames => {
                return Promise.all(
                    cacheNames.map(cacheName => {
                        if (cacheName !== STATIC_CACHE && cacheName !== DYNAMIC_CACHE) {
                            if (self.location.hostname === 'localhost') {
                                console.log('删除旧缓存:', cacheName);
                            }
                            return caches.delete(cacheName);
                        }
                    })
                );
            })
            .then(() => {
                return self.clients.claim();
            })
    );
});

// 拦截网络请求 - 智能缓存策略
self.addEventListener('fetch', event => {
    const { request } = event;
    const url = new URL(request.url);
    
    // 只处理同源请求
    if (url.origin !== location.origin) {
        return;
    }
    
    // 确定资源类型和缓存策略
    const resourceType = getResourceType(request);
    const strategy = getCacheStrategy(resourceType);
    
    event.respondWith(handleRequest(request, strategy, resourceType));
});

// 获取资源类型
function getResourceType(request) {
    const url = new URL(request.url);
    const pathname = url.pathname;
    
    if (pathname.match(/\.(png|jpg|jpeg|gif|webp|svg)$/i)) {
        return 'image';
    } else if (pathname.match(/\.(css|js)$/i)) {
        return 'static';
    } else if (pathname === '/' || pathname.endsWith('.html')) {
        return 'document';
    } else {
        return 'dynamic';
    }
}

// 获取缓存策略
function getCacheStrategy(resourceType) {
    switch (resourceType) {
        case 'image':
        case 'static':
            return 'cache-first';
        case 'document':
        case 'dynamic':
        default:
            return 'network-first';
    }
}

// 处理请求
function handleRequest(request, strategy, resourceType) {
    const cacheName = getCacheName(resourceType);
    
    if (strategy === 'cache-first') {
        return cacheFirst(request, cacheName);
    } else {
        return networkFirst(request, cacheName);
    }
}

// 获取缓存名称
function getCacheName(resourceType) {
    switch (resourceType) {
        case 'image':
            return IMAGE_CACHE;
        case 'static':
            return STATIC_CACHE;
        default:
            return DYNAMIC_CACHE;
    }
}

// 缓存优先策略
function cacheFirst(request, cacheName) {
    return caches.match(request)
        .then(cachedResponse => {
            if (cachedResponse && !isExpired(cachedResponse, cacheName)) {
                return cachedResponse;
            }
            
            return fetch(request)
                .then(response => {
                    if (response && response.status === 200) {
                        const responseToCache = response.clone();
                        caches.open(cacheName)
                            .then(cache => {
                                cache.put(request, responseToCache);
                            });
                    }
                    return response;
                })
                .catch(() => cachedResponse || new Response('离线模式', { status: 503 }));
        });
}

// 网络优先策略
function networkFirst(request, cacheName) {
    return fetch(request)
        .then(response => {
            if (response && response.status === 200) {
                const responseToCache = response.clone();
                caches.open(cacheName)
                    .then(cache => {
                        cache.put(request, responseToCache);
                    });
            }
            return response;
        })
        .catch(() => {
            return caches.match(request)
                .then(cachedResponse => {
                    if (cachedResponse) {
                        return cachedResponse;
                    }
                    // 文档请求的后备方案
                    if (request.destination === 'document') {
                        return caches.match('/index.html');
                    }
                    return new Response('离线模式', { status: 503 });
                });
        });
}

// 检查缓存是否过期
function isExpired(response, cacheName) {
    const dateHeader = response.headers.get('date');
    if (!dateHeader) return false;
    
    const cacheDate = new Date(dateHeader).getTime();
    const now = Date.now();
    const expiry = getExpiryTime(cacheName);
    
    return (now - cacheDate) > expiry;
}

// 获取过期时间
function getExpiryTime(cacheName) {
    if (cacheName === STATIC_CACHE) return CACHE_EXPIRY.static;
    if (cacheName === IMAGE_CACHE) return CACHE_EXPIRY.images;
    return CACHE_EXPIRY.dynamic;
}

// 后台同步
self.addEventListener('sync', event => {
    if (event.tag === 'background-sync') {
        if (self.location.hostname === 'localhost') {
            console.log('执行后台同步');
        }
        event.waitUntil(
            // 这里可以添加后台同步逻辑
            Promise.resolve()
        );
    }
});

// 推送通知
self.addEventListener('push', event => {
    if (event.data) {
        const data = event.data.json();
        const options = {
            body: data.body,
            icon: data.icon || '/icon-192x192.png',
            badge: '/badge-72x72.png',
            vibrate: [100, 50, 100],
            data: {
                dateOfArrival: Date.now(),
                primaryKey: data.primaryKey
            },
            actions: [
                {
                    action: 'explore',
                    title: '查看详情',
                    icon: '/images/checkmark.png'
                },
                {
                    action: 'close',
                    title: '关闭',
                    icon: '/images/xmark.png'
                }
            ]
        };
        
        event.waitUntil(
            self.registration.showNotification(data.title, options)
        );
    }
});

// 通知点击事件
self.addEventListener('notificationclick', event => {
    event.notification.close();
    
    if (event.action === 'explore') {
        event.waitUntil(
            clients.openWindow('/')
        );
    }
});

// 错误处理
self.addEventListener('error', event => {
    if (self.location.hostname === 'localhost') {
        console.error('Service Worker 错误:', event.error);
    }
});

self.addEventListener('unhandledrejection', event => {
    if (self.location.hostname === 'localhost') {
        console.error('Service Worker 未处理的 Promise 拒绝:', event.reason);
    }
});